package com.myzk.example.utils.secutity;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * base64 工具类 桥接org.apache.commons.codec.binary.Base64实现
 * @author mayong
 * @date 2020年04月06日22:05:03
 */
public class Base64Util {
    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    public static byte[] encode(byte[] src){
       return Base64.encodeBase64(src);
    }

    public static byte[] decode(byte[] src){
        return Base64.decodeBase64(src);
    }

    public static byte[] encodeBase64URLSafe(byte[] data){
        return Base64.encodeBase64URLSafe(data);
    }
    public static byte[] encode(String str){
        return encode(str,DEFAULT_CHARSET);
    }

    public static byte[] encode(String str,Charset charset){
        return encode(str.getBytes(charset));
    }

    public static byte[] decode(String str){
        return Base64.decodeBase64(str);
    }

    public static byte[] encodeBase64URLSafe(String str){
        return encodeBase64URLSafe(str,DEFAULT_CHARSET);
    }

    public static byte[] encodeBase64URLSafe(String str,Charset charset){
        return encodeBase64URLSafe(str.getBytes(charset));
    }

    public static String encodeToString(byte[] src){
        return new String(encode(src), StandardCharsets.US_ASCII);
    }

    public static String encodeToString(String src){
        return encodeToString(src,DEFAULT_CHARSET);
    }

    public static String encodeToString(String src, Charset charset){
        return encodeToString(src.getBytes(charset));
    }

    public static String encodeBase64URLSafeString(byte[] data){
        return new String(encodeBase64URLSafe(data));
    }

    public static String encodeBase64URLSafeString(String str){
        return encodeBase64URLSafeString(str,DEFAULT_CHARSET);
    }

    public static String encodeBase64URLSafeString(String str,Charset charset){
        return encodeBase64URLSafeString(str.getBytes(charset));
    }

    public static String decodeToString(byte[] src){
        return decodeToString(src,DEFAULT_CHARSET);
    }

    public static String decodeToString(byte[] src,Charset charset){
        return new String(decode(src),charset);
    }

    public static String decodeToString(String src){
        return decodeToString(src,DEFAULT_CHARSET);
    }

    public static String decodeToString(String src,Charset charset) {
        return new String(decode(src.getBytes()),charset);
    }

    public static void main(String[] args) {

        String gbkString = encodeToString("安徽合肥", Charset.forName("GBK"));
        System.out.println("gbkString = " + gbkString);

        String string = decodeToString(gbkString);
        System.out.println(string);
        String decodeGbkString = decodeToString(gbkString, Charset.forName("GBK"));
        System.out.println("decodeGbkString = " + decodeGbkString);

    }
}
